/**
 * API 请求拦截器
 *
 * @author Claude
 */

import type {AxiosError, AxiosInstance, InternalAxiosRequestConfig} from 'axios'

/**
 * 设置请求拦截器
 * @param client axios实例
 */
export function setupRequestInterceptor(client: AxiosInstance): void {
    client.interceptors.request.use(
        (config: InternalAxiosRequestConfig) => {
            // 从localStorage获取token
            // 通过initAuth()确保Pinia和localStorage同步
            const token = localStorage.getItem('accessToken')

            if (token) {
                config.headers.Authorization = `Bearer ${token}`
            }

            return config
        },
        (error: AxiosError) => {
            console.error('[API] 请求配置错误:', error)
            return Promise.reject(error)
        }
    )
}

/**
 * 设置所有拦截器
 * @param client axios实例
 */
export function setupInterceptors(client: AxiosInstance): void {
    setupRequestInterceptor(client)
}